// 带 TTL 的热门/推荐电影缓存（按用户隔离）。
// 目的：不同登录用户的首页推荐彼此独立，避免出现“所有账号看到同一批推荐”的问题。
// 存储结构：{ map: { [userKey]: { list, ts, ttl } }, ver: 2 }

const KEY = 'hot_movies_cache_v2' // 升级 KEY，避免旧版全局缓存干扰
const DEFAULT_TTL = 30 * 60 * 1000 // 30 分钟

function safeLoad() {
  try {
    if (typeof window === 'undefined' || !window.localStorage) return null
    const raw = window.localStorage.getItem(KEY)
    if (!raw) return null
    const obj = JSON.parse(raw)
    if (obj && typeof obj === 'object' && obj.map && typeof obj.map === 'object') {
      return obj
    }
    return null
  } catch {
    return null
  }
}

function safeSaveMap(map) {
  try {
    if (typeof window === 'undefined' || !window.localStorage) return
    const payload = { map, ver: 2 }
    window.localStorage.setItem(KEY, JSON.stringify(payload))
  } catch {
    // ignore
  }
}

function parseJwtUserId(token) {
  try {
    const base64Url = String(token).split('.')[1]
    if (!base64Url) return null
    const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
    const json = decodeURIComponent(atob(base64).split('').map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)).join(''))
    const payload = JSON.parse(json)
    const uid = payload && (payload.user_id ?? payload.uid ?? payload.sub)
    return uid != null ? String(uid) : null
  } catch {
    return null
  }
}

function currentUserKey() {
  try {
    if (typeof window === 'undefined') return 'guest'
    const t = window.localStorage ? window.localStorage.getItem('token') : null
    const uid = t ? parseJwtUserId(t) : null
    return uid ? `u_${uid}` : 'guest'
  } catch {
    return 'guest'
  }
}

export const hotMoviesCache = {
  _map: Object.create(null), // { [userKey]: { list, ts, ttl } }
  _loaded: false,
  _ensureLoaded() {
    if (this._loaded) return
    const data = safeLoad()
    if (data && data.map && typeof data.map === 'object') {
      this._map = data.map
    }
    this._loaded = true
  },
  _getBucket(userKey) {
    this._ensureLoaded()
    if (!this._map[userKey]) this._map[userKey] = { list: [], ts: 0, ttl: DEFAULT_TTL }
    return this._map[userKey]
  },
  set(list, ttlMs = DEFAULT_TTL) {
    const key = currentUserKey()
    const bucket = this._getBucket(key)
    bucket.list = Array.isArray(list) ? list : []
    bucket.ts = Date.now()
    bucket.ttl = ttlMs
    safeSaveMap(this._map)
  },
  clear(userKey) {
    const key = userKey || currentUserKey()
    this._ensureLoaded()
    this._map[key] = { list: [], ts: 0, ttl: DEFAULT_TTL }
    safeSaveMap(this._map)
  },
  isFresh(ttlMs = DEFAULT_TTL) {
    const key = currentUserKey()
    const bucket = this._getBucket(key)
    const ttl = typeof bucket.ttl === 'number' ? bucket.ttl : ttlMs
    return bucket.ts > 0 && (Date.now() - bucket.ts) <= ttl
  },
  get(ttlMs = DEFAULT_TTL) {
    const key = currentUserKey()
    const bucket = this._getBucket(key)
    const ttl = typeof bucket.ttl === 'number' ? bucket.ttl : ttlMs
    if (bucket.ts > 0 && (Date.now() - bucket.ts) <= ttl) return Array.isArray(bucket.list) ? bucket.list : []
    return []
  },
  // 仅用于调试：返回当前用户 key
  _currentKey() { return currentUserKey() }
}
